package com.dhcc.android.base.common.view;

import android.app.Activity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.dhcc.android.base.R;
import com.dhcc.android.base.common.adapter.SortAdapter;
import com.dhcc.android.base.common.bean.KeyValueBean;
import com.dhcc.android.base.common.bean.SortDatas;
import com.dhcc.android.base.common.bean.SortModel;
import com.dhcc.android.base.utils.Constants;
import com.dhcc.android.base.utils.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 此类为所有操作按钮的list Poupwindow
 *
 * @author pengling
 */
public class MyActorPopWindow {
    private MyPopupWindow popupWindow;
    private Activity activity;
    private SortAdapter adapter;
    View parent;
    private List<SortModel> sortModelList = new ArrayList<SortModel>();
    private String oldContent, oldId;
    private ArrayList<String> n;
    private SortDatas sortDatas;
    /**
     * @author 汉字转换成拼音的类
     */
    private Boolean isSingle;

    /**
     * @author 根据拼音来排列ListView里面的数据类
     */

    public MyActorPopWindow(Activity activity, View parentView, Boolean isSingle) {
        this.activity = activity;
        this.parent = parentView;
        this.isSingle = isSingle;
    }

    private View view;
    private TextView actorValue;
    private TextView actorId;

    public void showActorPanel(TextView actorId, TextView actorValue,
                               List<KeyValueBean> list, String beanType) {
        if (this.actorValue == null || this.actorId == null) {
            this.actorValue = actorValue;
            this.actorId = actorId;
        }
        if (popupWindow == null) {
            LayoutInflater layoutInflater = (LayoutInflater) activity
                    .getSystemService(activity.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.util_search, null);
            LinearLayout cancel = (LinearLayout) view.findViewById(R.id.cancel);
            cancel.setOnClickListener(itemsOnClickBtn);
            LinearLayout sure = (LinearLayout) view.findViewById(R.id.sure);
            if (isSingle) {
                sure.setVisibility(View.GONE);
            }
            sure.setOnClickListener(itemsOnClickBtn);
            WindowManager wm = (WindowManager) activity
                    .getSystemService(activity.WINDOW_SERVICE);
            int width = wm.getDefaultDisplay().getWidth();// 屏幕宽度
            popupWindow = new MyPopupWindow(view, width,
                    LayoutParams.FILL_PARENT, true);
        }
        sortDatas = new SortDatas();
        oldContent = actorValue.getText().toString();
        oldId = actorId.getText().toString();
        popupWindow.showAtLocation(parent, Gravity.TOP | Gravity.CENTER, 0, 0);// 显示在最中央的位置
        if (list != null && list.size() != 0) {// 选择框默认选中
            sortModelList = sortDatas.getSortModelListFromKeyValue(list);
            adapter = sortDatas.initViews(sortModelList, onItemClickListener,
                    view, activity, isSingle, beanType);
            if (!isSingle) {// 为多选
                String str[] = oldId.split(",");
                n = new ArrayList<String>();
                for (String string : str) {
                    initSelect(adapter, string, list);
                }
                if (n.size() != 0) {
                    adapter.setSelectedPosition(n);
                }
            } else {
                initSelect(adapter, oldId, list);
            }
        }
    }

    public void initSelect(SortAdapter sortAdapter, String key_str,
                           List<KeyValueBean> list) {
        for (int i = 0; i < list.size(); i++) {
            String item_str = list.get(i).getKey();
            if (item_str.equals(key_str)) {
                if (isSingle) {
                    sortAdapter.setSelectedPosition(item_str);
                } else {
                    n.add(item_str);
                }
            }
        }
    }

    OnClickListener itemsOnClickBtn = new OnClickListener() {
        public void onClick(View v) {
            // Constants.keyValueList=null;
            if (v.getId() == R.id.cancel) {
                actorValue.setText(oldContent);
                actorId.setText(oldId);
                popupWindow.dismiss();
            } else if (v.getId() == R.id.sure) {
                if (content.equals("") && !isClick) {//未点击 设值为原值
                    content = oldContent;
                    id = oldId;
                }
                setValue();
                popupWindow.dismiss();
            }
        }
    };
    OnItemClickListener onItemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            if (sortModelList != null) {
                SortModel sm = (SortModel) adapter.getItem(position);
                ImageView selectImage = (ImageView) view
                        .findViewById(R.id.select_item);
                setValueText(sm, selectImage);// 给输入框赋值
            }
        }
    };
    /**
     * 给输入框赋值
     *
     * @param name
     * @param selectImage
     */
    private String content = "";
    private String id = "";
    private Boolean isClick = false;

    public void setValueText(SortModel sm, ImageView selectImage) {
        isClick = true;
        String new_content = sm.getName();
        String new_id = sm.getId();
        if (StringUtil.isEmpty(content) || StringUtil.isEmpty(id)) {
            content = oldContent;
            id = oldId;
        }
        if (selectImage.getVisibility() == View.GONE) { // 组件不可见，处于未选中状态，可做选择操作。
            selectImage.setVisibility(View.VISIBLE);
            if (isSingle) { // 是单选
                content = new_content;
                id = new_id;
                setValue();
                // Constants.keyValueList=null;
                popupWindow.dismiss();
            } else {
                if (StringUtil.isEmpty(content)) {
                    content = new_content;
                    id = new_id;
                } else {
                    content = content + "," + new_content;
                    id = id + "," + new_id;
                }

            }
        } else {
            selectImage.setVisibility(View.GONE);
            if (StringUtil.isNotEmpty(content) && content.contains(new_content)) {
                content = content.replace(new_content, ",");
                id = id.replace(new_id, ",");
                content = content.replace(",,", "");
                id = id.replace(",,", "");
                //				int i = new_content.charAt(new_content.length() - 1);
                //				int j = content.charAt(content.length() - 1);

                //				if (content.equals(new_content) || i == j) {
                //					content = content.replaceAll("," + new_content, "");
                //					id = id.replaceAll("," + new_id, "");
                //					System.out.println("content1:"+content);
                //					if (StringUtil.isNotEmpty(content)) {
                //						content = content.replaceAll(new_content, "");
                //						id = id.replaceAll(new_id, "");
                //					}
                //					System.out.println("content2:"+content);
                //				} else {
                //					content = content.replaceAll(new_content + ",", "");
                //					id = id.replaceAll(new_id + ",", "");
                //				}
            }
        }

    }

    public void setValue() {
        if (StringUtil.isNotEmpty(content)) {
            content = content.replace(",,", "");
            id = id.replace(",,", "");
            if (content.startsWith(",")) {
                if (content.equals(",")) {
                    content = content.replace(",", "");
                    id = id.replace(",", "");
                } else {
                    content = content.substring(1, content.length());
                    id = id.substring(1, id.length());
                }
            }
        }
        if (actorValue != null) {
            if (StringUtil.isEmpty(content)) {
                if (!isSingle) {
                    actorValue.setText("");
                    actorId.setText("");
                } else {
                    actorValue.setText(oldContent);
                    actorId.setText(oldId);
                }
            } else {
                id = id.replace("暂无,", "");
                content = content.replace("暂无,", "");// 把暂无去掉
                actorId.setText(id);
                actorValue.setText(content);
            }
        }
    }


    //======================================================================

    private KeyValueBean kv;
    private OnSelectListener listener;
    private String mjkey;
    private String zwbh;
    private String tbkey;
    private String tbvalue;
    private double mj;

    /**
     * @param activity
     * @param parentView
     * @param kv         已选择的数据键、值对应的的字段名
     */
    public MyActorPopWindow(Activity activity, View parentView, KeyValueBean kv, OnSelectListener listener) {
        this.activity = activity;
        this.parent = parentView;
        this.kv = kv;
        this.listener = listener;
    }

    public MyActorPopWindow(Activity activity, View parentView, KeyValueBean kv, String zwbh, OnSelectListener listener, String mjkey, double mj) {
        this.activity = activity;
        this.parent = parentView;
        this.kv = kv;
        this.listener = listener;
        this.mjkey = mjkey;
        this.mj = mj;
        this.zwbh = zwbh;
    }

    /**
     * 弹出选择列表
     *
     * @param datas    列表数据
     * @param selects  已经选择的数据
     * @param beanType 分组类型
     */
    public void show(List<KeyValueBean> datas, List<Map<String, String>> selects, String beanType, boolean isSingle) {
        this.isSingle = isSingle;

        if (!isSingle) {
            results = Constants.setListToList(selects, results);
        }
        if (popupWindow == null) {
            //渲染
            LayoutInflater layoutInflater = (LayoutInflater) activity
                    .getSystemService(activity.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.util_search, null);
            LinearLayout cancel = (LinearLayout) view.findViewById(R.id.cancel);
            cancel.setOnClickListener(viewClick);
            LinearLayout sure = (LinearLayout) view.findViewById(R.id.sure);
            if (isSingle) {
                sure.setVisibility(View.GONE);
            } else {
                sure.setOnClickListener(viewClick);
            }
            //设置宽高
            WindowManager wm = (WindowManager) activity
                    .getSystemService(activity.WINDOW_SERVICE);
            int width = wm.getDefaultDisplay().getWidth();// 屏幕宽度
            popupWindow = new MyPopupWindow(view, width,
                    LayoutParams.FILL_PARENT, true);
        }

        sortDatas = new SortDatas();
        popupWindow.showAtLocation(parent, Gravity.TOP | Gravity.CENTER, 0, 0);// 显示在最中央的位置
        //处理数据

        List<String> ids = getSelectIds(datas, selects);
        if (datas != null && datas.size() != 0) {// 选择框默认选中
            sortModelList = sortDatas.getSortModelListFromKeyValue(datas);
            adapter = sortDatas.initViews(sortModelList, itemclick,
                    view, activity, isSingle, beanType);
            if (!isSingle) {// 为多选
                if (selects != null) {
                    n = new ArrayList<String>();
                    for (String id : ids) {
                        initSelect(adapter, id, datas);
                    }
                    if (n.size() != 0) {
                        adapter.setSelectedPosition(n);
                    }
                }
            }
        }
    }

    private List<String> getSelectIds(List<KeyValueBean> list, List<Map<String, String>> selects) {
        List<String> ids = new ArrayList<String>();
        if (list != null && list.size() > 0 && selects != null && selects.size() > 0) {
            for (KeyValueBean keyValueBean : list) {
                String key = keyValueBean.getKey();
                String selectValue = keyValueBean.getValue();
                if (selects.size() > 1) {// 多个
                    for (Map<String, String> map : selects) {
                        String str = map.get(kv.getKey());
                        if (StringUtil.isNotEmpty(selectValue)
                                && str.contains(selectValue)) {
                            ids.add(key);
                        }
                    }
                } else {// 只有一个
                    String str = selects.get(0).get(kv.getKey());
                    if (str.contains(selectValue)) {
                        ids.add(key);
                    }
                }
            }
        }
        return ids;
    }

    OnClickListener viewClick = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.cancel) {
                popupWindow.dismiss();
            } else if (v.getId() == R.id.sure) {
                //保存选中的值

                if (listener != null) {
                    listener.onSelect(results);
                }
                popupWindow.dismiss();
            }
        }
    };

    private List<Map<String, String>> results = new ArrayList<Map<String, String>>();
    OnItemClickListener itemclick = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            SortModel sm = (SortModel) adapter.getItem(position);
            ImageView selectImage = (ImageView) view.findViewById(R.id.select_item);

            if (selectImage.getVisibility() == View.GONE) { // 组件不可见，处于未选中状态，可做选择操作。
                selectImage.setVisibility(View.VISIBLE);

                Map<String, String> map = new HashMap<String, String>();
                map.put(zwbh, sm.getId());
                map.put(kv.getKey(), valueFormatter(sm));

                String mu = "0", pfm = "0";
//				MyDemandActivity act = (MyDemandActivity) activity;
//				if(act.mj_dv > 0){
//					if(act.oldUnit == 1){
//						mu = String.valueOf(act.mj_dv);
//						pfm = CommenUtil.MUtoPFM(String.valueOf(act.mj_dv));
//					}else{
//						mu = CommenUtil.PFMtoMU(String.valueOf(act.mj_dv));
//						pfm = String.valueOf(act.mj_dv);
//					}
//				}
//				System.out.println("--选择了--mjkey:"+mjkey);
//				map.put(mjkey, mu);
//				map.put("MJPFM", pfm);
//				map.put(act.tbkey, act.tbvalue);

                System.out.println("列表选择：" + map);
                if (isSingle) {
                    if (listener != null) {
                        listener.OnSingleSelect(map);
                    }
                    popupWindow.dismiss();
                } else {
                    results.add(map);
                }

            } else {
                selectImage.setVisibility(View.GONE);

                for (Map<String, String> map : results) {
                    if (map.get(kv.getKey()).contains(sm.getName())) {
                        results.remove(map);
                        break;
                    }
                }
            }
        }
    };


    /**
     * 格式化 值
     */
    private String valueFormatter(SortModel sm) {
        String value = sm.getName();
        String input = kv.getFieldset();
        if (input.endsWith("1") || input.contains("1|")) {
            value = sm.getName() + "(" + sm.getId() + ")";
        } else if (input.endsWith("2") || input.contains("2|")) {
            value = sm.getName();
        } else if (input.endsWith("3") || input.contains("3|")) {
            value = sm.getName();
        }

        return value;
    }

    public interface OnSelectListener {
        public void onSelect(List<Map<String, String>> results);

        public void OnSingleSelect(Map<String, String> map);
    }


    //============产量调查作物选择===============
    public MyActorPopWindow(Activity activity, View parentView, OnSelectListener listener) {
        this.activity = activity;
        this.parent = parentView;
        this.listener = listener;
    }

    /**
     * 弹出选择列表
     *
     * @param datas    列表数据
     * @param selects  已经选择的数据
     * @param beanType 分组类型
     */
    public void show(List<KeyValueBean> datas, List<Map<String, String>> selects, KeyValueBean kv, boolean isSingle) {
        this.isSingle = isSingle;
        this.kv = kv;
        if (!isSingle) {
            results = Constants.setListToList(selects, results);
        }
        if (popupWindow == null) {
            //渲染
            LayoutInflater layoutInflater = (LayoutInflater) activity
                    .getSystemService(activity.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.util_search, null);
            LinearLayout cancel = (LinearLayout) view.findViewById(R.id.cancel);
            cancel.setOnClickListener(viewClick);
            LinearLayout sure = (LinearLayout) view.findViewById(R.id.sure);
            if (isSingle) {
                sure.setVisibility(View.GONE);
            } else {
                sure.setOnClickListener(viewClick);
            }
            //设置宽高
            WindowManager wm = (WindowManager) activity
                    .getSystemService(activity.WINDOW_SERVICE);
            int width = wm.getDefaultDisplay().getWidth();// 屏幕宽度
            popupWindow = new MyPopupWindow(view, width,
                    LayoutParams.FILL_PARENT, true);
        }

        sortDatas = new SortDatas();
        popupWindow.showAtLocation(parent, Gravity.TOP | Gravity.CENTER, 0, 0);// 显示在最中央的位置
        //处理数据

        List<String> ids = getZWSelectIds(datas, selects);
        if (datas != null && datas.size() != 0) {// 选择框默认选中
            sortModelList = sortDatas.getSortModelListFromKeyValue(datas);
            adapter = sortDatas.initViews(sortModelList, itemclick2,
                    view, activity, isSingle, Constants.SortBeanTypeByField);
            if (!isSingle) {// 为多选
                if (selects != null) {
                    n = new ArrayList<String>();
                    for (String id : ids) {
                        initSelect(adapter, id, datas);
                    }
                    if (n.size() != 0) {
                        adapter.setSelectedPosition(n);
                    }
                }
            }
        }
    }

    private List<String> getZWSelectIds(List<KeyValueBean> list, List<Map<String, String>> selects) {
        List<String> ids = new ArrayList<String>();
        if (list != null && list.size() > 0 && selects != null && selects.size() > 0) {
            for (KeyValueBean keyValueBean : list) {
                String key = keyValueBean.getKey();
                if (selects.size() > 1) {// 多个
                    for (Map<String, String> map : selects) {
                        String str = map.get(kv.getKey());
                        if (StringUtil.isNotEmpty(key)
                                && str.equals(key)) {
                            ids.add(key);
                        }
                    }
                } else {// 只有一个
                    String str = selects.get(0).get(kv.getKey());
                    if (str.equals(key)) {
                        ids.add(key);
                    }
                }
            }
        }
        return ids;
    }

    OnItemClickListener itemclick2 = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            SortModel sm = (SortModel) adapter.getItem(position);
            ImageView selectImage = (ImageView) view.findViewById(R.id.select_item);

            if (selectImage.getVisibility() == View.GONE) { // 组件不可见，处于未选中状态，可做选择操作。
                selectImage.setVisibility(View.VISIBLE);

                Map<String, String> map = new HashMap<String, String>();
                map.put(kv.getKey(), sm.getId());
                map.put(kv.getValue(), sm.getName());
                System.out.println("列表选择：" + map);
                if (isSingle) {
                    if (listener != null) {
                        listener.OnSingleSelect(map);
                    }
                    popupWindow.dismiss();
                } else {
                    results.add(map);
                }

            } else {
                selectImage.setVisibility(View.GONE);

                for (Map<String, String> map : results) {
                    if (map.get(kv.getKey()).equals(sm.getId())) {
                        results.remove(map);
                        break;
                    }
                }
            }
        }
    };
}
